package ldh.msg.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import ldh.msg.helper.MsgConstants;
import ldh.msg.helper.MsgDialog;

import org.apache.log4j.Logger;

public class MsgReceiver extends Thread {
	static final Logger log = Logger.getLogger("test");
	private MsgSocketPool[] sockpool = null;
	private java.util.LinkedList<Integer> list = new java.util.LinkedList<Integer>();	
	private int port = 0;
	
	public MsgReceiver(int port, int poolSize) {
		try {			
			this.port = port;
			if (this.port == MsgConstants.MSG_PORT) {
				sockpool = new MsgMsgPool[poolSize];
				for(int i = 0; i < poolSize; i++) {
					//log.debug("socket pool index [" + i + "]");
					Integer index = new Integer(i);
					sockpool[i] = new MsgMsgPool(this, index);
					sockpool[i].start();
				}
			} else if (this.port == MsgConstants.FILE_PORT){
				sockpool = new MsgFilePool[poolSize];
				for(int i = 0; i < poolSize; i++) {
					//log.debug("socket pool index [" + i + "]");
					Integer index = new Integer(i);
					sockpool[i] = new MsgFilePool(this, index);
					sockpool[i].start();
				}
			}
		} catch (Exception e) {
			
		}
	}
	
	public void run() {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(this.port);
			log.debug("create socket!");
		} catch (IOException ioe) {
			log.error(" IOException : " + ioe.getMessage());			
			new MsgDialog().failRunDialog();
		} catch (SecurityException sece) {
			log.error(" SecurityException : " + sece.getMessage());
			System.exit(-1);
		}
		int client = 0;
		synchronized (this) {
			Socket socket = null;
			while(true) {
				
				try {
					socket = serverSocket.accept();
					if (list.size() != 0) {
						client = dequeue();
						sockpool[client].setSocket(socket);
						release(sockpool[client]);
						//log.debug(" server socket open!!! : " + client);						
					} else {
						log.debug(" server socket close!!!");
						try {
							socket.close();							
						} catch (IOException ioe) {
							log.error(ioe.getMessage());
						}
					}
					notify();
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			}
		}
	}
	
	public void setMsgSocketPool(Integer i) {
		//log.debug(" set Pool : " + i);
		list.addLast(i);
		//log.debug("pool size : " + list.size());
		sockpool[i.intValue()].threadNotify();
	}
	
	public void release(MsgSocketPool sockpool) {
		sockpool.threadNotify();
	}
	
	public synchronized int dequeue() {
		int i = ((Integer)list.getFirst()).intValue();
		list.removeFirst();
		//log.debug(" remove list size : " + list.size());
		return i;
	}
	
	public static void main (String args[]) {
		log.debug("Socket Daemon Start!!! ");
		new MsgReceiver(6713, 10).start();
	}
	
}

